﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mijiaxueche.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace mijiaxueche.weixin.help
{
    /// <summary>
    /// 微信发送消息方法 只有48小时有互动的才能接收
    /// </summary>
    public class Send
    {

        /// <summary>
        /// 使用客服接口推送消息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        private string PostByKF(string param)
        {
            return
                HttpHelper.webRequestPost(
                    "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" +
                    wxHelper.getToken(), param);
        }

        /// <summary>
        /// 使用模版消息接口推送消息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        private string PostByTemplate(string param)
        {
            return
                HttpHelper.webRequestPost(
                    "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" +
                    wxHelper.getToken(), param);
        }

        /// <summary>
        /// 向用户发送文本消息
        /// </summary>
        /// <param name="touser">接受消息用户的openid</param>
        /// <param name="text">消息内容</param>
        /// <param name="sendCount">当前发送次数：0-失败时自动重发，1-不重发</param>
        /// <returns>返回是否成功</returns>
        public int SendText(string touser, string text, int sendCount = 0)
        {
            Logger.Info("推送微信消息：" + text);
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{{\"touser\":\"{0}\",\"msgtype\":\"text\",\"text\":{{\"content\":\"{1}\"}}}}", touser, text);
            string result = PostByKF(sb.ToString());
            JObject ja = (JObject)JsonConvert.DeserializeObject(result);
            //{"errcode":42001,"errmsg":"access_token expired hint: [icKzQA0298age9]"}

            if (ja["errcode"].ToString() == "0") //成功发送
            {
                return 0;
            }
            else if (ja["errcode"].ToString() == "42001") //access_token 已过期
            {
                wxHelper.UpdateToken(); //刷新access_token
                if (sendCount == 0)
                {
                    return SendText(touser, text, 1);
                }
                else
                {
                    return 42001;
                }
            }
            else //其它异常
            {
                if (sendCount == 0)
                {
                    return SendText(touser, text, 1);
                }
                else
                {
                    return Convert.ToInt32(ja["errcode"].ToString());
                }
            }
        }

        ///// <summary>
        ///// 发送图文消息// </summary>
        ///// <param name="touser">接受消息用户的openid</param>
        ///// <param name="list">图文消息列表</param>
        ///// <param name="sendCount">当前发送次数：0-失败时自动重发，1-不重发</param>
        ///// <returns></returns>
        //public int SendNews(string touser, List<article> list, int sendCount = 0)
        //{
        //    if (list == null || list.Count == 0)
        //    {
        //        return -2;
        //    }
        //    StringBuilder sb = new StringBuilder();
        //    StringBuilder articles = new StringBuilder();
        //    for (int i = 0; i < list.Count && i < 8; i++)
        //    {
        //        articles.AppendFormat(",{{\"title\":\"{0}\",\"description\":\"{1}\",\"url\":\"{2}\",\"picurl\":\"{3}\"}}", list[i].title.Replace("\"", "\\\""), list[i].description.Replace("\"", "\\\""), list[i].url.Replace("\"", "\\\""), list[i].picurl.Replace("\"", "\\\""));
        //    }
        //    sb.AppendFormat("{{\"touser\":\"{0}\",\"msgtype\":\"news\",\"news\":{{\"articles\": [{1}]}}}}", touser, articles.ToString().Substring(1));
        //    string result = PostByKF(sb.ToString());
        //    JObject ja = (JObject)JsonConvert.DeserializeObject(result);
        //    if (ja["errcode"].ToString() == "0")//成功发送
        //    {
        //        return 0;
        //    }
        //    else if (ja["errcode"].ToString() == "42001") //access_token 已过期
        //    {
        //        GetAccessToken.GetAccessToken2Cache();//刷新access_token
        //        if (sendCount == 0)
        //        {
        //            return SendNews(touser, list, 1);
        //        }
        //        else
        //        {
        //            return 42001;
        //        }
        //    }
        //    else//其它异常
        //    {
        //        if (sendCount == 0)
        //        {
        //            return SendNews(touser, list, 1);
        //        }
        //        else
        //        {
        //            return Convert.ToInt32(ja["errcode"].ToString());
        //        }
        //    }
        //}

        /// <summary>
        /// 发送图文消息
        /// </summary>
        /// <param name="touser">接受消息用户的openid</param>
        /// <param name="text">带[]json格式的图文消息内容</param>
        /// <param name="sendCount">当前发送次数：0-失败时自动重发，1-不重发</param>
        /// <returns></returns>
        public int SendNews(string touser, string text, int sendCount = 0)
        {
            if (string.IsNullOrEmpty(text))
            {
                return -2;
            }
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("{{\"touser\":\"{0}\",\"msgtype\":\"news\",\"news\":{{\"articles\": {1}}}}}", touser, text);
            string result = PostByKF(sb.ToString());
            JObject ja = (JObject)JsonConvert.DeserializeObject(result);
            if (ja["errcode"].ToString() == "0") //成功发送
            {
                return 0;
            }
            else if (ja["errcode"].ToString() == "42001") //access_token 已过期
            {
                wxHelper.UpdateToken();
                if (sendCount == 0)
                {
                    return SendNews(touser, text, 1);
                }
                else
                {
                    return 42001;
                }
            }
            else //其它异常
            {
                if (sendCount == 0)
                {
                    return SendNews(touser, text, 1);
                }
                else
                {
                    return Convert.ToInt32(ja["errcode"].ToString());
                }
            }
        }

        /// <summary>
        /// 推送模版消息
        /// </summary>
        /// <param name="touser">接收人OPENID</param>
        /// <param name="json">json格式的内容（键值对形式）</param>
        /// <param name="template_id">微信模版ID</param>
        /// <param name="sendCount"></param>
        /// <returns></returns>
        public int SendTemplate(string touser, string json, string template_id, string strUri, int sendCount = 0)
        {
            Logger.Info("推送微信消息模版：template_id：" + template_id + "strUri:" + strUri + "json:" + json + "touser:" + touser);
            if (string.IsNullOrEmpty(json) || string.IsNullOrEmpty(template_id))
            {
                return -2;
            }

            StringBuilder sb = new StringBuilder();
            StringBuilder text = new StringBuilder(); //data 数据内容
            Dictionary<string, string> d = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
            foreach (string key in d.Keys)
            {
                //,\"color\":\"#173177\" 内容的颜色可加在value后面
                text.AppendFormat(",\"{0}\": {{\"value\":\"{1}\",\"color\":\"#173177\"}}", key, d[key]);
            }

            sb.AppendFormat(
                "{{\"touser\":\"{0}\",\"template_id\":\"{1}\",\"url\":\"{3}\",\"data\":{{{2}}}}}",
                touser, template_id, text.Remove(0, 1).ToString(), strUri);
            string result = PostByTemplate(sb.ToString());
            JObject ja = (JObject)JsonConvert.DeserializeObject(result);
            if (ja["errcode"].ToString() == "0") //成功发送
            {
                return 0;
            }
            else if (ja["errcode"].ToString() == "42001" || ja["errcode"].ToString() == "40001") //access_token 已过期
            {
                wxHelper.UpdateToken(); //刷新access_token
                if (sendCount == 0)
                {
                    return SendTemplate(touser, json, template_id, strUri, 1);
                }
                else
                {
                    return Convert.ToInt32(ja["errcode"].ToString());
                }
            }
            else //其它异常
            {
                if (sendCount == 0)
                {
                    return SendTemplate(touser, json, template_id, strUri, 1);
                }
                else
                {
                    return Convert.ToInt32(ja["errcode"].ToString());
                }
            }
        }
    }
}
